package com.imu.utils;

import com.imu.security.SessionKeys;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    public static String doPost(String url,String param,String sign) {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(80000)
                .setSocketTimeout(50000).setConnectTimeout(80000).build();
        httpPost.setConfig(config);
        httpPost.addHeader(SessionKeys.SIGN.toString(),sign);
        String respContent = null;
        //json方式
        StringEntity entity = new StringEntity(param,"utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        try {
            HttpResponse resp = client.execute(httpPost);
            if (resp.getStatusLine().getStatusCode() == 200) {
                HttpEntity he = resp.getEntity();
                respContent = EntityUtils.toString(he, "UTF-8");
            }
        }catch (Exception e){
            logger.error("doPost",e);
            return null;
        }finally {
            if(client != null){
                try {
                    client.close();
                }catch (Exception e){
                    logger.error("doPost",e);
                }
            }
        }

        return respContent;
    }


}
